var createError = require('http-errors');
var express = require('express');
var session = require('express-session');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// 引入工具类
var jwtUtils = require('./utils/jwtUtil');

// ①引用路由
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

//配置中间件 maxAge单位为ms
app.use(session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
    cookie: ('name', 'value', {maxAge: 5*60*1000,secure: false})
}))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

global.globalname='zz'

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//定义全局的加解密秘钥
global.globalKey = '123456'

app.use(async function(req,resp,next){
    let path = req.path;

    if(path.startsWith('/users/login') || path.startsWith('/users/regist')){
        next();
    }else{
        //从请求头里头拿到令牌
        let token = req.headers.token;
        if(!token){
            //非常规情况（文件下载，没有办法设置请求头，或者比如获取验证码）
            token = req.query.token
        }
        let result = await jwtUtils.verifysync(token,global.globalKey)

        if(result.err){
            // throw new Error(result.msg)
            resp.status(500);
            resp.send(result.msg);
        }else{
            req.headers.session = result
            //表示执行下一步动作
            next();
        }
    }


    // if(req.path !='/mine.html' && req.path !='/user/login' && req.path !='/user/register'){
    //     let token = req.headers.token;
    //     safeInterceptor.verify(token,global.secretKey,function(user){
    //         req.headers.sessionData = user;
    //         next();
    //     },function(err){
    //         next();
    //     })
    // }else{
    //     next();
    // }
})


//②路由注册
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   res.send('404')
// });

// error handler
app.use(function(err, req, res, next) {
    res.status(500)
    res.send(err.message)
});

module.exports = app;
